import {
  getMyPromotionCommission,
  queryPromotionCommissionList
} from "../../../service/jb_promotion_service"

import {
  queryShareQrCode
} from "../../../service/jb_common_service"
import {
  extractRecord,
} from "../../../service/jb_scoreAndMoney_service"
import mathUtil from "../../../tools/mathUtils/mathUtil"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowQRCode: false,
    userInfo: {
      nickname: "",
      avatar: "",
    },
    item:
    {
      "attrId": null,
      "productId": 8,
      "cartNum": 1,
      "image": "https://images.jiabao19.com/images/public/content/2023/12/25/e7cc3b3a51114ec1a5bd8cd1a38b10ad6pzWKadEgO.jpg",
      "storeName": "测试2",
      "price": "1.02",
      "isReply": null,
      "sku": null

    },
    menuTop: app.globalData.menuButton.top,
    menuHeight: app.globalData.menuButton.height,
    newDataList: [
      {
        title: "推广名片",
        icon: "https://images.jiabao19.com/common/Iconly_Glass_Gallery.png",
        navUrl: "",
      },
      {
        title: "推广人统计",
        icon: "https://images.jiabao19.com/common/Iconly_Glass_Graph.png",
        navUrl: "/featurePackage/pages/promotion/promotionPeople/promotionPeople",
      },
      {
        title: "推广人订单",
        icon: "https://images.jiabao19.com/common/Iconly_Glass_Document.png",
        navUrl: "/featurePackage/pages/promotion/promotionOrder/promotionOrder",
      },
    ],
    currentType: 0, //0:佣金订单，1：提现记录
    orDataList: [
      {
        title: "推广名片",
        icon: "https://images.jiabao19.com/mine/tg_mp.png",
        navUrl: "",
      },
      {
        title: "推广人统计",
        icon: "https://images.jiabao19.com/mine/tg_rtj.png",
        navUrl: "/featurePackage/pages/promotion/promotionPeople/promotionPeople",
      },
      {
        title: "佣金明细",
        icon: "https://images.jiabao19.com/mine/tg_yj.png",
        navUrl: "/featurePackage/pages/promotion/promotionCommission/promotionCommission",
      },
      {
        title: "推广人订单",
        icon: "https://images.jiabao19.com/mine/tg_da.png",
        navUrl: "/featurePackage/pages/promotion/promotionOrder/promotionOrder",
      },
      {
        title: "推广人排行",
        icon: "https://images.jiabao19.com/mine/tg_reph.png",
        navUrl: "/featurePackage/pages/promotion/promotionPeopleRank/promotionPeopleRank",
      },
      {
        title: "佣金排行",
        icon: "https://images.jiabao19.com/mine/tg_yjph.png",
        navUrl: "/featurePackage/pages/promotion/promotionCommissionRank/promotionCommissionRank",
      },
    ],
    commissionData: {
      commissionCount: "0.00",
      extractCount: "0",
      lastDayCount: "0",
      preCommission: "0.00",
      frozenPrice: "0.00",
    },
    agreeCommission: 0.00,
    isShowBindPop: false,//是否弹出绑定支付宝弹窗
    isBindAiPay: false,//是否已绑定支付宝
    qrCode: "",//个人分享二维码
    showRemindPop: false,//当前佣金
    showYjPop: false,//预计佣金
    showWaitPop: false,//待提现

    page: 1,
    limit: 10,
    dateLimit: '',
    commissionStatus: "",
    dataList: [],
    isShowLoading: false,//加载状态出现
    isBottomShow: false,//是否没有更多数据了
    refreshFlag: false,
    statusMap: {
      0: '待发货',
      1: '待收货',
      2: '待评价',
      3: '已完成',
      4: '已退款',
    },
    refundStautsMap: {
      1: '退款申请中',
      2: '已退款'
    },
    newScrollTop: 0,
    newOffsetTop: 0,

    commissonStatusMap: {
      0: '预收益',
      1: '预收益',
      2: '待提现',
      3: '已提现',
      4: '退款',
      5: '提现中',
    },
    inviteCode: null,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      userInfo: app.globalData.userInfo
    })
    this.queryShareQrCode();
    this.queryPromotionCommissionList("refresh");
    this.getInviteCode();
  },

  getInviteCode() {
    this.setData({
      inviteCode: this.encryptNumber(parseInt(app.globalData.userId)).toUpperCase()
    })
  },
  //加密方法
  encryptNumber(num) {
    // 确保数字在合理范围内
    if (num < 0 || num >= Math.pow(36, 6)) {
      throw new Error("数字超出可编码范围");
    }

    const charSet = 'abcdefghijklmnopqrstuvwxyz0123456789';
    let encryptedStr = '';

    // 循环处理直到数字为0
    while (num > 0) {
      let remainder = num % 36; // 使用36进制（26个字母+10个数字）
      encryptedStr = charSet[remainder] + encryptedStr;
      num = Math.floor(num / 36);
    }

    // 如果长度不足6位，在前面补充字符。这里以'a'为例，实际可根据需求调整
    while (encryptedStr.length < 6) {
      encryptedStr = 'a' + encryptedStr;
    }

    return encryptedStr.substring(0, 6); // 确保最终长度不超过6位
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getMyPromotionCommission();
  },
  //加密生成邀请码

  pushToScore() {
    wx.navigateTo({
      url: '/featurePackage/pages/commissionExpain/commissionExpain',
    })
  },
  pushToCommission() {
    wx.navigateTo({
      url: '/featurePackage/pages/promotion/promotionCommission/promotionCommission?commission=' + this.data.commissionData.totalCount,
    })
  },
  //弹出提示框
  showRemindPopAction(e) {
    let index = e.currentTarget.dataset.index;
    if (index == 0) {
      //当前佣金解释
      this.setData({
        showRemindPop: true,
      })
    } else if (index == 1) {
      //预计佣金提示
      this.setData({
        showYjPop: true,
      })
    } else if (index == 2) {
      this.setData({
        showWaitPop: true,
      })
    }
  },
  pushToWithDraw() {
    wx.navigateTo({
      url: '/featurePackage/pages/applyWithdraw/applyWithdraw?money=' + this.data.commissionData.commissionCount,
    })
  },
  queryShareQrCode() {
    let data = {
      params: {
        u: app.globalData.userId,
      },
      page: "pages/home/home"
    }
    queryShareQrCode(data).then(res => {
      console.log("JJLog:获取到的个人二维码来了：" + JSON.stringify(res))
      if (res.code == 200) {
        this.setData({
          qrCode: res.data.code || ""
        })
      }
    }).catch(err => {

    })
  },
  switchChange(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      currentType: index,
      page: 1,
      isBottomShow: false,
    })
    if (index == 0) {
      this.queryPromotionCommissionList('refresh');
    } else {
      this.queryExtractChangeList('refresh')
    }

  },
  //下拉刷新
  handleRefresh() {
    // TODO
    this.setData({
      page: 1,
      isBottomShow: false,
      refreshFlag: true,
    })
    if (this.data.currentType == 0) {
      this.queryPromotionCommissionList('refresh');
    } else {
      this.queryExtractChangeList('refresh')
    }

  },
  handleLoadmore() {
    console.log('加载更多');
    if (this.data.isBottomShow) {
      return;
    }
    this.setData({
      isShowLoading: true,
      page: this.data.page + 1
    })
    if (this.data.currentType == 0) {
      this.queryPromotionCommissionList('');
    } else {
      // this.queryShareQrCode('');
      this.queryExtractChangeList('refresh')
    }
  },

  queryPromotionCommissionList(type) {
    wx.showLoading();
    queryPromotionCommissionList(this.data.page, this.data.limit, this.data.commissionStatus, this.data.dateLimit).then(res => {
      wx.hideLoading();
      if (res.code == 200 && res.data) {
        let arr = (type == 'refresh' ? [] : this.data.dataList || []);
        arr = arr.concat(res.data.list || [])
        this.setData({
          dataList: arr,
          refreshFlag: false,
          isShowLoading: false,

          isBottomShow: res.data.totalPage == this.data.page ? true : false,
        })
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '加载失败',
        icon: "none"
      })
      if (this.data.page != 1) {
        this.setData({
          page: this.data.page - 1
        })
      }
      this.setData({
        refreshFlag: false,
      })
      console.error('JJLog:queryPromotionCommissionList', err);
    })
  },
  // onScroll(event) {
  //   console.log("JJJ:laimmmmmm===")
  //   wx.createSelectorQuery()
  //     .select('#scroller')
  //     .boundingClientRect((res) => {
  //       console.log("JJLog:res.top:" + res.top);
  //       this.setData({
  //         newScrollTop: event.detail.scrollTop,
  //         newOffsetTop: res.top,
  //       });
  //     })
  //     .exec();


  // },
  copyInviteCode() {
    wx.setClipboardData({
      data: this.data.inviteCode,
      success: function (res) {
        wx.showToast({
          title: '复制邀请码成功'
        })
        // wx.getClipboardData({
        //   success: function (res) {
        //     wx.showToast({
        //       title: '复制邀请码成功'
        //     })
        //   },
        //   fail: function (err) {
        //     wx.showToast({
        //       title: '复制失败',
        //       icon: "none"
        //     })
        //   }
        // })
      },
      fail: function (err) {
        wx.showToast({
          title: '复制失败',
          icon: "none"
        })
      }
    })
  },
  //提现记录
  queryExtractChangeList(type) {
    wx.showLoading();
    extractRecord(this.data.page, this.data.limit).then(res => {
      wx.hideLoading();
      if (res.code == 200 && res.data) {
        let arr = (type == 'refresh' ? [] : this.data.dataList || []);
        arr = arr.concat(res.data.list || [])
        this.setData({
          dataList: arr,
          refreshFlag: false,
          isShowLoading: false,
          isBottomShow: res.data.totalPage == this.data.page ? true : false,
        })
      }
    }).catch(err => {
      console.error("JJLog:extractRecord", err);
      wx.hideLoading();
      wx.showToast({
        title: err || '加载失败',
        icon: "none"
      })
      if (this.data.page != 1) {
        this.setData({
          page: this.data.page - 1
        })
      }
      this.setData({
        refreshFlag: false,
      })
    })
  },


  getMyPromotionCommission() {
    wx.showLoading();
    getMyPromotionCommission().then(res => {
      wx.hideLoading();
      if (res.code == 200) {
        let totalCount = mathUtil.add(res.data.commissionCount, res.data.preCommission)
        totalCount = mathUtil.add(totalCount, res.data.frozenPrice)
        totalCount = mathUtil.add(totalCount, res.data.extractCount || 0)
        totalCount = mathUtil.add(totalCount, res.data.extractingCommission || 0)
        res.data.totalCount = totalCount
        res.data.preCount = mathUtil.add(res.data.frozenPrice, res.data.preCommission)
        this.setData({
          commissionData: res.data
        })
        // if (res.data.commissionCount > 0 && !app.globalData.userInfo.aliAccount) {
        //   setTimeout(() => {
        //     this.setData({
        //       isShowBindPop: true,
        //     })
        //   }, 1000)

        // }
        // if (res.data.commissionCount > 0) {
        //   let reNum = mathUtil.sub(res.data.commissionCount, res.data.frozenPrice)
        //   this.setData({
        //     agreeCommission: reNum
        //   })
        // }
      }
    }).catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err || '加载失败',
        icon: "none"
      })
      console.error('JJLog:getMyPromotionCommission', err);
    })
  },
  pushToWithdrawRecord() {
    wx.navigateTo({
      url: '/featurePackage/pages/totalWithdrawRecord/totalWithdrawRecord',
    })
  },
  //去绑定支付宝
  pushToBindAiPay() {
    this.setData({
      isShowBindPop: false,
    })
    wx.navigateTo({
      url: '/featurePackage/pages/bindAiPay/bindAiPay',
    })
  },

  pushToPage(e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.newDataList[index];
    if (item.navUrl) {
      if (item.title == '佣金明细') {
        wx.navigateTo({
          url: item.navUrl + "?commission=" + this.data.commissionData.commissionCount,
        })
      } else {
        wx.navigateTo({
          url: item.navUrl,
        })
      }

    } else {
      //推广名片
      this.setData({
        isShowQRCode: true,
      })
    }
  },



  hideQRPopup() {
    this.setData({
      isShowQRCode: false,
      showRemindPop: false,
      showYjPop: false,
      showWaitPop: false,
    })
  },
  //复制订单号
  copyOrderNo(e) {
    let text = e.currentTarget.dataset.text;
    wx.setClipboardData({
      data: text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '订单号复制成功',
              icon: "none"
            })
          },
          fail: function (err) {
            wx.showToast({
              title: '复制失败',
              icon: "none"
            })
          }
        })
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})